<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-19
 * Time: 14:42
 */

namespace app\api\service\phone;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\facade\Cache;

class GetPhoneCodeSer extends Token
{
    // 用户ID
    private $uid;

    private $tel;

    function __construct($tel)
    {
        $this->uid = self::getCurrentUid();
        $this->tel = $tel;
    }

    // 使用阿里云短信验证码
    public function getSms()
    {
        $values = Cache::get($this->uid);
        if ($values) {
            $now_time = time();
            $time = $values['time'] + 300;
            if ($now_time < $time) {
                throw new ParameterException([
                    'msg' => [
                        'sms' => '请勿频繁发送验证码'
                    ]
                ]);
            }
        }
        return $this->setAliSms();
    }

    /**
     * 发送验证码
     */
    private function setAliSms()
    {
        $code = rand(100000, 999999);
        AlibabaCloud::accessKeyClient(config('aliyun.access_key_id'), config('aliyun.access_key_secret'))
            ->regionId('cn-hangzhou')// replace regionId as you need
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->scheme('https')// https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $this->tel,
                        'SignName' => config('aliyun.sign_name'),
                        'TemplateCode' => config('aliyun.template_code'),
                        'TemplateParam' => "{'code':" . $code . "}",
                    ],
                ])->request();
            $dataOne = $result->toArray();
            $res = $this->MessageHandle($dataOne);
            if ($dataOne['Code'] == 'OK') {
                $expire_in = config('setting.token_expire_in');
                $cacheValue['time'] = time();
                $cacheValue['code'] = $code;
                $cacheValue['phone'] = $this->tel;
                cache($this->uid, $cacheValue, $expire_in);
                return writeJson(200, [], '获取成功！');
            } else {
                throw new ParameterException([
                    'msg' => [
                        'sms' => $res
                    ]
                ]);
            }
        } catch (ClientException $e) {
            throw $e;
        } catch (ServerException $e) {
            throw $e;
        }
    }

    /**
     * 返回码
     */
    private function MessageHandle($message)
    {
        $result = "";
        switch ($message['Code']) {
            case "OK":
                $result = "短信发送成功！";
                break;
            case "isp.RAM_PERMISSION_DENY":
                $result = "RAM权限DENY";
                break;
            case "isv.OUT_OF_SERVICE":
                $result = "业务停机";
                break;
            case "isv.PRODUCT_UN_SUBSCRIPT":
                $result = "未开通云通信产品的阿里云客户";
                break;
            case "isv.PRODUCT_UNSUBSCRIBE":
                $result = "产品未开通";
                break;
            case "isv.ACCOUNT_NOT_EXISTS":
                $result = "账户不存在";
                break;
            case "isv.ACCOUNT_ABNORMAL":
                $result = "账户异常";
                break;
            case "isv.SMS_TEMPLATE_ILLEGAL":
                $result = "短信模板不合法";
                break;
            case "isv.SMS_SIGNATURE_ILLEGAL":
                $result = "短信签名不合法";
                break;
            case "isv.INVALID_PARAMETERS":
                $result = "参数异常";
                break;
            case "isv.MOBILE_NUMBER_ILLEGAL":
                $result = "非法手机号";
                break;
            case "isv.MOBILE_COUNT_OVER_LIMIT":
                $result = "手机号码数量超过限制";
                break;
            case "isv.TEMPLATE_MISSING_PARAMETERS":
                $result = "模板缺少变量";
                break;
            case "isv.BUSINESS_LIMIT_CONTROL":
                $result = "业务限流";
                break;
            case "isv.INVALID_JSON_PARAM":
                $result = "JSON参数不合法，只接受字符串值";
                break;
            case "isv.PARAM_LENGTH_LIMIT":
                $result = "参数超出长度限制";
                break;
            case "isv.PARAM_NOT_SUPPORT_URL":
                $result = "不支持URL";
                break;
            case "isv.AMOUNT_NOT_ENOUGH":
                $result = "账户余额不足";
                break;
            case "isv.TEMPLATE_PARAMS_ILLEGAL":
                $result = "模板变量里包含非法关键字";
                break;
        }
        return $result;
    }
}